from threading import Thread

from django.core import serializers
from django.shortcuts import render
from m.indexapi import index as indexApi
from django.http import HttpResponse
import json

# Create your views here.
from m.models import Content

from m.taobao.Crawler import Crawler

from m.models import Reptile
from m.models import user
from m.models import goods
from m.models import liekGoods

from m.models import ReptileSetting

from m.CF import TF


def daogou(request):
    '''收页'''
    data = indexApi.api.index(request)
    if data is not False:
        return render(request, 'daogou.html', {'data': data})
    return render(request, 'daogou.html')


def search(request):
    data = indexApi.api.search(request)
    if data is not False:
        return render(request, 'search.html', {'data': data})
    return render(request, 'search.html')


def page(request):
    '''分页'''
    data = indexApi.api.index(request)
    if data is not False:
        return render(request, 'page.html', {'data': data})
    return HttpResponse('')


def guangyiguang(request):
    data = indexApi.api.search(request)
    if data is not False:
        return render(request, 'guangyiguang.html', {'data': data})
    return render(request, 'guangyiguang.html')


def main(request):
    try:
        data = indexApi.api.search(request)
    except Exception:
        return render(request, 'main.html')
    # 这里需要改成自己本地的路径
    with open('C:\\Users\\liujie\\PycharmProjects\\TaoBaoKeDemo\\mobileProject\\m\\taobao\\result.txt', 'r') as load_f:
        load_dict = json.load(load_f)
    print(load_dict)
    if data is not False:
        return render(request, 'main.html', {'data': data, 'result': load_dict})
    return render(request, 'main.html')


def daogouars(request):
    data = {}
    content = Content.objects.all()
    from django.core import serializers
    data['list'] = json.loads(serializers.serialize("json", content))
    from django.http import JsonResponse
    i = 0
    for itme in data['list']:
        data['list'][i]['fields']['id'] = i
        data['list'][i]['fields']['sub'] = data['list'][i]['fields']['content'][0:60]
        i = i + 1
        print(i)
    print(data)
    return render(request, 'arts.html', data)


def setting(request):
    return render(request, 'setting.html')


# 添加爬虫配置
def addreptileSetting(request):
    searchurl = request.GET.get('searchurl')
    category = request.GET.get('category')
    username = request.GET.get('username')
    user_pwd = request.GET.get('user_pwd')
    rs = ReptileSetting(searchurl=searchurl, category=category, username=username, user_pwd=user_pwd)
    rs.save()
    return HttpResponse("配置成功")


# 获取爬虫配置
def reptileSettingList(request):
    data = {}
    content = ReptileSetting.objects.all()
    from django.core import serializers
    data['list'] = json.loads(serializers.serialize("json", content))
    return HttpResponse(data)


def h_setting(request):
    username = request.GET.get('username')
    userpwd = request.GET.get('userpwd')
    category = request.GET.get('category')
    searchurl = request.GET.get('searchurl')
    print(username)
    print(userpwd)
    print(category)
    print(searchurl)
    result = Reptile.objects.filter(searchkey=searchurl)
    if result:
        return HttpResponse('该链接已经爬取了')
    Crawler().start(username, userpwd, searchurl, category)
    return HttpResponse('爬取成功')


def login(request):
    print(request.body)
    user_name = request.POST.get("user_name")
    user_pwd = request.POST.get("user_pwd")
    print(user_name)
    datas = user.objects.filter(user_name=user_name, user_pwd=user_pwd).values('id', 'user_name')
    print(datas)
    data = {}
    if datas.count() == 0:
        data["code"] = 0
        data["message"] = "账号密码不存在"
        return HttpResponse(json.dumps(data))
    data["info"] = list(datas)[0]
    data["code"] = 1
    data["message"] = "登录成功"
    print(data)
    return HttpResponse(json.dumps(data))


def register(request):
    print(request.body)
    user_name = request.POST.get("user_name")
    user_pwd = request.POST.get("user_pwd")
    user_phone = request.POST.get("user_phone")
    user_head = request.POST.get("user_head")
    user_sex = request.POST.get("user_sex")
    sex = 2
    if user_sex == "男":
        sex = 1
    user_age = request.POST.get("user_age")
    print(user_name)
    datas = user(user_name=user_name, user_pwd=user_pwd, user_phone=user_phone, user_head=user_head, user_sex=sex,
                 user_age=user_age)
    datas.save()
    data = {"code": 1, "message": "注册成功"}
    return HttpResponse(json.dumps(data))


def home(request):
    user_id = request.POST.get("user_id")
    print(user_id)
    data = {"code": 1, "message": "查询成功"}
    content = goods.objects.all().values()
    data['list'] = list(content)
    print(data)
    return HttpResponse(json.dumps(data))

#用户协同过滤推荐算法
def regoods(request):
    user_id = request.POST.get("user_id")
    goods_id = request.POST.get("goods_id")
    print(user_id)
    likes = liekGoods.objects.all().values('user_id','goods_id')  # 库里所有的用户和商品直接的关系
    print(likes)
    gds = goods.objects.all().values()  # 库里所有的商品数据
    users = user.objects.all().values('id')  # 库里所有的用户数据
    allUserGoodsStarList = [[0] * gds.count() for i in range(users.count())]
    tfUsers = []
    for us in users:
        tfUsers.append(str(us['id']))
    tfGoods = []
    for good in gds:
        tfGoods.append(str(good['id']))
    for i in range(len(tfUsers)):
        uid = tfUsers[i]
        lst = allUserGoodsStarList[i]
        for j in range(len(lst)):
            gid = tfGoods[j]
            for lke in likes:
                if str(lke['user_id']) == uid and str(lke['goods_id']) == gid:
                    allUserGoodsStarList[i][j] = 1

    print(allUserGoodsStarList)
    print(tfUsers)
    print(tfGoods)
    data = TF(tfUsers, tfGoods, allUserGoodsStarList).calrecommendGood(user_id)
    resultData = {"code": 1, "message": "推荐成功"}
    resut=[]
    for rgood in gds:
        if str(rgood['id']) in data:
            resut.append(rgood)
    print(len(data))
    print(len(resut))
    print(len(tfGoods))
    print(resut)
    resultData['list']=resut
    # {"code": 1, "message": "\u67e5\u8be2\u6210\u529f",
    # "list": [{"id": 1, "goods_id": 121, "user_id": 1, "goods_fraction": 3}, {"id": 2, "goods_id": 122, "user_id": 1, "goods_fraction": 4}, {"id": 3, "goods_id": 123, "user_id": 1, "goods_fraction": 4}]}
    return HttpResponse(json.dumps(resultData))


def like(request):
    user_id = request.POST.get("user_id")
    goods_id = request.POST.get("goods_id")
    goods_fraction = request.POST.get("goods_fraction")
    print(user_id)
    print(goods_id)
    print(goods_fraction)
    datas = liekGoods.objects.filter(user_id=user_id, goods_id=goods_id)
    if datas.count() == 0:
        liekGoods(user_id=user_id, goods_id=goods_id, goods_fraction=goods_fraction).save()
        data = {"code": 1, "message": "添加成功"}
        return HttpResponse(json.dumps(data))

    data = {"code": 0, "message": "已经喜欢了这个商品"}
    return HttpResponse(json.dumps(data))
